<template>
  <div class="main-container">
    <TableHeadSearch @searchForm="searchForm" queryCode="workOrderList"/>
    <TableHeader :can-collapsed="false">
      <template v-slot:right>
        <el-button
          type="primary"
          size="mini"
          :icon="CirclePlus"
          v-if="isShowed('workOrder:add')"
          @click="onAddItem"
          >新增
        </el-button>
        <el-button
          type="danger"
          size="mini"
          :icon="Delete"
          v-if="isShowed('workOrder:delete')"
          @click="onDeleteItem(selectRows)"
          >删除
        </el-button>
      </template>
    </TableHeader>
    
    <TableBody
      ref="tableBody"
      :tableLoading="tableLoading"
      :tableConfig="tableConfig"
      :tableColumns="tableColumns"
      :tableOperations="tableOperations"
      :tableData="dataList"
    >
      <template #tableConfig>
        <div
          class="flex justify-between padding"
          style="border-bottom: 1px dashed var(--el-border-color-light)"
        >
          <el-link :underline="false">表格设置</el-link>
          <div>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.border">表格边框</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.stripe">斑马纹</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.multiSelect">多选</el-checkbox>
            </span>
            <el-tooltip effect="dark" content="刷新页面" placement="top">
              <el-button
                circle
                type="success"
                :icon="RefreshIcon"
                size="mini"
                @click="doRefresh"
              />
            </el-tooltip>
            <SortableTable
              class="margin-left"
              :table-props="tableColumns"
              @update="onUpdateTable"
            />
          </div>
        </div>
      </template>
    </TableBody>
    <TableFooter
      ref="tableFooter"
      @refresh="doRefresh"
      @pageChanged="doRefresh"
    />
   
  <Dialog ref="dialog" title="编辑信息" :form-items="formItems">
      <template #content>
        <BaseForm
          ref="baseForm"
          :form-items="formItems"
        ></BaseForm>
      </template>
  </Dialog>
  </div>
</template>


<script lang="tsx" setup>
import { ElMessage } from 'element-plus';
import {onMounted, reactive, ref } from "vue";

import {
  showConfirmBox,
  showErrorMessage,
  showInfoMessage,
  showSuccessMessage,
} from "@/components/types";
import { useDataTable, usePost } from "@/hooks";
import { queryWorkOrderList,saveWorkOrder,updateWorkOrder,deleteBatchWorkOrder } from "@/api/url";
import type { TableFooter,BaseFormType, DialogType } from "@/components/types";
import {
  Delete,
  CirclePlus,
  Refresh as RefreshIcon,
} from "@element-plus/icons";
import { isShowed } from '@/utils/index';
const {
  handleSuccess,
  selectRows,
  dataList,
  tableConfig,
  tableLoading,
  handleSelectionChange,
} = useDataTable();
const post = usePost();
const tableColumns = reactive([
  { label: "标签", 
    prop: "flag", 
    checked:true,
  },
  { label: "发布时间", 
    prop: "publishDate", 
    checked:true,
  },
  { label: "接单时间", 
    prop: "receiveDate", 
    checked:true,
  },
  { label: "描述", 
    prop: "remark", 
    checked:true,
  },
  { label: "标题", 
    prop: "title", 
    checked:true,
  },
  { label: "要求", 
    prop: "demand", 
    checked:true,
  },
  { label: "内容", 
    prop: "content", 
    checked:true,
  },
  { label: "状态", 
    prop: "state", 
    checked:true,
  },

]);
const tableOperations = reactive([
  {
    text: "编辑",
    key: "edit",
    type: "primary",
    code: "workOrder:edit",
    isShow:true,
    handler: (row: any) => handleEdit(row),
  },
]);

const formItems = reactive([
  { label: "发布用户", 
    type: 'select',
    name: "publishUserOid", 
    value: 0 ,
    maxlength: 20,
    placeholder: '请输入发布用户OID',
    selectOptions: {},
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = 0 ;
            },
  },
  { label: "标签", 
    type: 'input',
    name: "flag", 
    value: '',
    maxlength: 20,
    placeholder: '请输入标签',
        validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "发布时间", 
    type: 'datetime',
    name: "publishDate", 
    value: '',
    maxlength: 20,
    placeholder: '请输入发布时间',
        validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "接单时间", 
    type: 'datetime',
    name: "receiveDate", 
    value: '',
    maxlength: 20,
    placeholder: '请输入接单时间',
        validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "描述", 
    type: 'textarea',
    name: "remark", 
    value: '',
    maxlength: 20,
    placeholder: '请输入描述',
        validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "接单用户", 
    type: 'select',
    name: "receiveUserOid", 
    value: 0 ,
    maxlength: 20,
    placeholder: '请输入接单用户OID',
    selectOptions: {},
    validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = 0 ;
            },
  },
  { label: "标题", 
    type: 'input',
    name: "title", 
    value: '',
    maxlength: 20,
    placeholder: '请输入标题',
        validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "要求", 
    type: 'input',
    name: "demand", 
    value: '',
    maxlength: 20,
    placeholder: '请输入要求',
        validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "内容", 
    type: 'textarea',
    name: "content", 
    value: '',
    maxlength: 20,
    placeholder: '请输入内容',
        validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },
  { label: "工单OID", 
    type: 'number',
    name: "workOrderOid", 
    value: 0 ,
    maxlength: 20,
    placeholder: '请输入工单OID',
    hidden: true,
    reset() {
                this.value = 0 ;
            },
  },
  { label: "版本号", 
    type: 'number',
    name: "versionNo", 
    value: 0 ,
    maxlength: 20,
    placeholder: '请输入版本号',
    hidden: true,
    reset() {
                this.value = 0 ;
            },
  },
  { label: "状态", 
    type: 'input',
    name: "state", 
    value: '',
    maxlength: 20,
    placeholder: '请输入状态',
        validator: (item: any) => {
                if (!item.value) {
                    ElMessage.error(item.placeholder);
                    return false;
                }
                return true;
            }, 
    reset() {
                this.value = "";
            },
  },

]);
const tableFooter = ref<TableFooter>();
const dialog = ref<DialogType>();
const baseForm = ref<BaseFormType>();
function handleEdit(data: any) {
  onUpdateItem(data);
}
const onUpdateItem = (item: any) => {
  formItems.forEach((it) => {
    const propName = item[it.name];
    it.value = propName;
  });
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(updateWorkOrder,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
  });
};
let searchParam: any;
function doRefresh() {
   let params = {
     searchConditionVOList:searchParam,
     page: tableFooter.value?.withPageInfoData(),
  }
  queryList(queryWorkOrderList,params);
}

function queryList(url: string, params: any) {
  post({
    url: url,
    data: params,
  })
    .then((res: any) => {
      const obj = {
        data: res.data,
      };
      handleSuccess(obj);
      tableFooter.value?.setTotalSize(res.pageUI.total);
    })
    .catch(console.log);
}

function submitForm(submitUrl: string ,params: any) {
   post({
    url: submitUrl,
    data: params,    
  })
  .then((res: any) => {
     ElMessage.success("数据提交成功！");
     doRefresh();
  })
  .catch(console.log);
}

const onAddItem = () => {
  baseForm.value?.resetParams();
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(saveWorkOrder,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
   
  });
};

function onDeleteItem(data: any) {
  if (data.length > 0) {
    showConfirmBox("是否要删除此数据项，删除后不恢复？", "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        let params: number[] = [];
        data.forEach((item: { workOrderOid: any }) => {
          params.push(item.workOrderOid);
        });
        post({
          url: deleteBatchWorkOrder,
          data: {
            keyOids: params,
          },
        })
          .then(() => {
            doRefresh();
            showSuccessMessage("删除成功");
          })
          .catch(console.log);
      })
      .catch(() => {
        showInfoMessage("取消删除");
      });
  } else {
    showErrorMessage("请选择要删除的数据项");
  }
}

function searchForm(data: any) {
    searchParam = data;
    let params = {
        searchConditionVOList: data,
        page: tableFooter.value?.withPageInfoData(),
  }
  queryList(queryWorkOrderList,params);
}

function onUpdateTable(temp: Array<TablePropsType>) {
  tableColumns.length = 0;
  tableColumns.push(...temp.filter((it: TablePropsType) => it.checked));
}

onMounted(doRefresh);
</script>
<style lang="scss" scoped>
.avatar-container {
  position: relative;
  width: 30px;
  height: 30px;
  margin: 0 auto;
  vertical-align: middle;
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
  .avatar-vip {
    border: 2px solid #cece1e;
  }
  .vip {
    position: absolute;
    top: 0;
    right: -9px;
    width: 15px;
    transform: rotate(60deg);
  }
}
.gender-container {
  .gender-icon {
    width: 20px;
  }
}
</style>
